<template>
	<view class="container">
		<view class="tipBox">
			<p style="text-align: center;">说明</p>
			<text>
				本人已充分知晓使用乐刷支付POS产品，已认真阅读《用户协议》，知悉使用时需支付0元服务费，该费用乐刷不予退还。我司没有代办信用卡或类似业务，如推销人员承诺代办信用卡等其他事项，均与乐刷无关。</text>
		</view>
		<view>
			<text>签字区</text>
		</view>

		<view class="canvesBox">
			<view class="wrapper">
				<view class="handCenter">
					<canvas class="handWriting" :disable-scroll="true" @touchstart="uploadScaleStart"
						@touchmove="uploadScaleMove" canvas-id="handWriting"></canvas>
				</view>
			</view>
		</view>
		<view class="tipBox">
			本人确认填写及提交的所有内容均为本人真实合法有效的个人信息。
		</view>
		<view class="buttonBox">
			<view class="btn-box">
				<button @click="retDraw" class="btn delBtn">重写</button>
				<button @click="saveCanvasAsImg" class="btn saveBtn">提交</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		nextTick
	} from "vue";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		onlyNumberReg,
		onlyCnReg
	} from "@/utils/regExp";

	import {
		showToast
	} from "@/utils/toast";
	import {
		queryMerchants,
		createMerchant
	} from "@/api/mine";
	import {
		useStore
	} from "@/store/index";
	import {
		singleTerminalQuery
	} from "@/api/common";
	import {
		uploadSignImage
	} from "@/api/upload";
	/** store实例 */
	const store = useStore();
	// OSS签名
	let ossConfig = ref({});
	let canvasName = ref('handWriting');
	let ctx = ref('');
	let startX = ref(null);
	let startY = ref(null)
	let canvasWidth = ref(0)
	let canvasHeight = ref(0)
	let selectColor = ref('black')
	let lineColor = ref('#1A1A1A')
	let lineSize = ref(5)
	let name = ref('')
	// 商户类型
	let type = ref(null)
	// 设备sn
	let currentSn = ref(null)
	// 接收创建商户数据
	let infomation = ref(null)
	// 签字图
	let commitmentLetter = ref()
	let lsMerInfoSucced = ref(null) //是否进行视频实名
	let queryParams = ref({
		image: ''

	});
	onLoad(async (params) => {
		if (params.info) { // 函数可把字符串作为 URI 组件进行编码
			let obj = JSON.parse(decodeURIComponent(params.info))
			console.log("obj-obj", obj)
			infomation.value = obj
			console.log("infomation.value", infomation.value)
		}
		type.value = params.type
		currentSn.value = params.sn
		console.log("shopFrontImgId=" + infomation.value.supplementaryInformation ? infomation.value
			.supplementaryInformation.shopFrontImgId : '');
		// oss签名配置
		// ossConfig.value = await getOsssSignature("agent");
		ctx.value = uni.createCanvasContext("handWriting");
		nextTick(() => {
			uni.createSelectorQuery().select('.handCenter').boundingClientRect(rect => {
					canvasWidth.value = rect.width;
					canvasHeight.value = rect.height;
					/* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
					setCanvasBg('#fff');
				})
				.exec();
		});
	})
	// 笔迹开始
	const uploadScaleStart = (e) => {
		startX.value = e.changedTouches[0].x
		startY.value = e.changedTouches[0].y
		//设置画笔参数
		//画笔颜色
		ctx.value.setStrokeStyle(lineColor.value)
		//设置线条粗细
		ctx.value.setLineWidth(lineSize.value)
		//设置线条的结束端点样式
		ctx.value.setLineCap("round") //'butt'、'round'、'square'
		//开始画笔
		ctx.value.beginPath()
	}
	// 笔迹移动
	const uploadScaleMove = (e) => {
		//取点
		let temX = e.changedTouches[0].x
		let temY = e.changedTouches[0].y
		//画线条
		ctx.value.moveTo(startX.value, startY.value)
		ctx.value.lineTo(temX, temY)
		ctx.value.stroke()
		startX.value = temX
		startY.value = temY
		ctx.value.draw(true)
	}
	const setCanvasBg = (color) => {

		/* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
		//rect() 参数说明  矩形路径左上角的横坐标，左上角的纵坐标, 矩形路径的宽度, 矩形路径的高度
		//这里是 canvasHeight - 4 是因为下边盖住边框了，所以手动减了写
		ctx.value.rect(0, 0, canvasWidth.value, canvasHeight.value - 4);
		// ctx.setFillStyle('red')
		ctx.value.setFillStyle(color);
		ctx.value.fill(); //设置填充
		ctx.value.draw(); //开画
	}
	/**
	 * 重写
	 */
	const retDraw = () => {
		ctx.value.clearRect(0, 0, 700, 730);
		ctx.value.draw();
		//设置canvas背景
		setCanvasBg('#fff');
	}

	//生成图片
	const saveCanvasAsImg = () => {

		if (!startX.value || !startY.value) {
			uni.showToast({
				title: '请签字',
				icon: 'none'
			})
			return
		}
		uni.canvasToTempFilePath({
			canvasId: 'handWriting',
			fileType: 'png',
			quality: 1, //图片质量
			success: (res) => {
				console.log('签名：res', res.tempFilePath)
				queryParams.value.image = res.tempFilePath;
				uploadSignImage(queryParams.value)
					.then((res) => {
						console.log("签名提交成功后res", res)
						commitmentLetter.value = res
						submitEvent()

					})
			}
		});
	}
	// 提交表单
	function submitEvent() {
		lsMerInfoSucced = store.lsMerInfoSucced;
		console.log("lsMerInfoSucced=" + lsMerInfoSucced);
		console.log("infomation.value", infomation.value)
		let obj = {
			baseInfo: {
				storeInfo: {
					type: type.value,
					storeName: infomation.value.businessInformation ? infomation.value.businessInformation
						.registerName : '商户' + '_' + infomation.value.corporateInformation.name,
					licenseImg: infomation.value.businessInformation ? infomation.value.businessInformation
						.licenseImage : '',
					licenseNo: infomation.value.businessInformation ? infomation.value.businessInformation.licenseNo :
						'',
					licenseBegin: infomation.value.businessInformation ? infomation.value.businessInformation
						.licenseBegin : '',
					licenseEnd: infomation.value.businessInformation ? infomation.value.businessInformation
						.licenseEnd : '',
					longTermLicense: infomation.value.businessInformation ? infomation.value.businessInformation
						.longTermLicense : '',
					operateProvinceCode: infomation.value.businessInformation ? infomation.value.businessInformation
						.provinceId : '',
					operateCityCode: infomation.value.businessInformation ? infomation.value.businessInformation
						.cityId : '',
					operateDistrictCode: infomation.value.businessInformation ? infomation.value.businessInformation
						.areaId : '',
					operateAddress: infomation.value.businessInformation ? infomation.value.businessInformation
						.registerAddress : '',
					mccId: infomation.value.businessInformation ? infomation.value.businessInformation.type : ''
				},
				operatorInfo: {
					idCardFront: infomation.value.corporateInformation ? infomation.value.corporateInformation
						.idCardFront : '',
					idCardBack: infomation.value.corporateInformation ? infomation.value.corporateInformation
						.idCardBack : '',
					name: infomation.value.corporateInformation ? infomation.value.corporateInformation.name : '',
					idCardNo: infomation.value.corporateInformation ? infomation.value.corporateInformation.idCardNo :
						'',
					idCardBegin: infomation.value.corporateInformation ? infomation.value.corporateInformation
						.idCardBegin : '',
					idCardEnd: infomation.value.corporateInformation ? infomation.value.corporateInformation
						.idCardEnd : '',
					phone: infomation.value.settlementInformation ? infomation.value.settlementInformation.phone : '',
					handImg: infomation.value.supplementaryInformation ? infomation.value.supplementaryInformation
						.handleIdCard : '',
					longTermIdCard: infomation.value.corporateInformation ? infomation.value.corporateInformation
						.longTermIdCard : '',
					idAddress: infomation.value.corporateInformation ? infomation.value.corporateInformation
						.idAddress : ''
				},
				operatorPhoto: {
					storefrontImg: infomation.value.supplementaryInformation ? infomation.value
						.supplementaryInformation.image : '',
					premisesImg: infomation.value.supplementaryInformation ? infomation.value.supplementaryInformation
						.interiorImage : '',
					ashierImg: infomation.value.supplementaryInformation ? infomation.value.supplementaryInformation
						.cashierImage : ''
				}
			},
			settlementInfo: {
				settleBankCardImg: infomation.value.settlementInformation ? infomation.value.settlementInformation
					.image : '',
				accountName: infomation.value.settlementInformation ? infomation.value.settlementInformation.name : '',
				cardNo: infomation.value.settlementInformation ? infomation.value.settlementInformation.cardNo : '',
				bankId: infomation.value.settlementInformation ? infomation.value.settlementInformation.bankId : '',
				type: 'PRIVATE',
				corporation: true,
				idCardFront: infomation.value.corporateInformation ? infomation.value.corporateInformation
					.idCardFront : '',
				idCardBack: infomation.value.corporateInformation ? infomation.value.corporateInformation.idCardBack :
					'',
				name: infomation.value.corporateInformation ? infomation.value.corporateInformation.name : '',
				idCardNo: infomation.value.corporateInformation ? infomation.value.corporateInformation.idCardNo : '',
				idCardBegin: infomation.value.corporateInformation ? infomation.value.corporateInformation
					.idCardBegin : '',
				idCardEnd: infomation.value.corporateInformation ? infomation.value.corporateInformation.idCardEnd :
					'',
				longTermIdCard: infomation.value.corporateInformation ? infomation.value.corporateInformation
					.longTermIdCard : '',
				idAddress: infomation.value.corporateInformation ? infomation.value.corporateInformation.idAddress : ''
			},
			otherParam: {
				commitmentLetter: commitmentLetter.value
			},
			settlementRate: {
				period: 'T1',
				ysfCreditCard: infomation.value.settlementRate.ysfCreditCard,
				ysfDebitCard: infomation.value.settlementRate.ysfDebitCard,
				ysf: infomation.value.settlementRate.ysf,
				wechat: infomation.value.settlementRate.wechat,
				alipay: infomation.value.settlementRate.alipay
			},
			sn: currentSn.value,
			oemUserNo: 'BU100002',
			userId: store.userInfo.userId
		}
		console.log("obj999", obj)
		createMerchant(obj)
			.then((res) => {
				showToast("创建成功", "none");
				console.log("res-res", res);
				// uni.navigateBack({
				// 	delta: 2 // 默认值是1，表示返回的页面层数
				// });


				if (lsMerInfoSucced == "0") {
					let idCardInfo = {
						frontUrl: infomation.value.corporateInformation ? infomation.value.corporateInformation
							.idCardFront : '',
						backUrl: infomation.value.corporateInformation ? infomation.value.corporateInformation
							.idCardBack : '',
						signId: commitmentLetter.value,
						shopFrontImgId: infomation.value.supplementaryInformation ? infomation.value
							.supplementaryInformation.shopFrontImgId : '',

						shopIndoorImgId: infomation.value.supplementaryInformation ? infomation.value
							.supplementaryInformation.shopIndoorImgId : '',
						shopCashierImgId: infomation.value.supplementaryInformation ? infomation.value
							.supplementaryInformation.shopCashierImgId : ''
					}
					uni.redirectTo({
						url: `/authentication/video/index?info= ${encodeURIComponent(JSON.stringify(idCardInfo))}`
					});
				} else {
					uni.navigateBack({
						delta: 2 // 默认值是1，表示返回的页面层数
					});
				}

				// 关闭页面
				// merchantStatus(currentSn.value)
			})
			.catch((err) => {

			});
	}

	// 查询设备状态
	// const merchantStatus = (val) => {
	// 	singleTerminalQuery(val)
	// 		.then((res) => {
	// 			console.log("res", res)
	// 			let id = val || '4f58e18c-a414-4cf3-9ef1-65baa1b4cdd7'
	// 			let status = res.status || 'WAIT'
	// 			let sn = res.sn
	// 			let reveal = res.reveal
	// 			uni.navigateTo({
	// 				url: `/pagesLogin/bindSuccess/index?id=${id}&status=${status}&sn=${sn}&reveal=${reveal}`,
	// 			});
	// 		})
	// 		.catch((err) => {

	// 		});
	// }
</script>

<style lang="scss" scoped>
	@import './index.scss';
</style>